package me.yuzho.study.concurrency;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/** Automatically give each thread its own storage
 *  根除对变量的共享防止共享变量在线程之间的冲突，线程本地存储是一种自动化机制，使用线程可以与状态联系起来
 * @author yzhou-citrix
 *
 */

class Accessor implements Runnable {

    private final int id;
    
    public Accessor(int idn) {
        id = idn;
    }
    
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            ThreadLocalVariableHolder.increment();
            System.out.println(this);
            Thread.yield();
        }
    }

    @Override
    public String toString() {
        return String.format("#%d: %d", id, ThreadLocalVariableHolder.get());
    }
    
    
}

public class ThreadLocalVariableHolder {

    private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
        private Random rand = new Random(47);
        @Override
        protected synchronized Integer initialValue() {
            return rand.nextInt(10000);
        } 
    };
    
    public static void increment() {
        value.set(value.get() + 1);
    }

    public static int get() {
        return value.get();
    }
    
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        IntStream.range(0, 5).forEach(i -> {
            executor.execute(new Accessor(i));
        });
        
        TimeUnit.SECONDS.sleep(3);
        executor.shutdownNow();
        
        System.out.println(ThreadLocalVariableHolder.get());
    }
}
